import Dialog from '@/components/Dialog';
import TextButton from '@/components/TextButton';
import React, { useCallback, useContext, useState } from 'react';
import AddPerson from './AddPerson';
import classes from './index.module.css';
import { AthletesContext } from './index.context';
import { AppContext } from '@/store/index.context';
import { getOptionLabel } from '@/utils/form.util';
import { SEX_OPTIONS } from '@/configs/options.config';
import { Person } from '@/types/persons';
import BlockButton from '@/components/BlockButton';
import TabHeader from '@/components/TabHeader';

export default function Athletes() {
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [editPerson, setEditPerson] = useState<Person>();
  const { personStore, messageStore } = useContext(AppContext);

  const handleAdd = useCallback(function () {
    setEditPerson(undefined);
    setShowAddDialog(true);
  }, []);

  const handleRemove = useCallback(
    function (person: Person) {
      messageStore.confirm('确定删除吗?', () => {
        personStore.removePerson(person);
      });
    },
    [personStore, messageStore],
  );

  const handleEdit = useCallback(function (person: Person) {
    setEditPerson(person);
    setShowAddDialog(true);
  }, []);

  return (
    <AthletesContext.Provider value={{ setShowAddDialog, editPerson }}>
      <TabHeader title="人员管理" />
      <div className={classes.Athletes}>
        <div>
          <BlockButton type="primary" onClick={handleAdd} text="添加人员" />
        </div>
        <ul className={classes.Persons}>
          <li>
            <span>姓名</span>
            <span>性别</span>
            <span>出生年月</span>
            <span>对局数</span>
            <span>操作</span>
          </li>
          {personStore.showPersons.map(person => (
            <li key={person.id}>
              <span>{person.name}</span>
              <span>{getOptionLabel(SEX_OPTIONS, person.sex)}</span>
              <span>{person.birthday}</span>
              <span>10</span>
              <span>
                <TextButton onClick={() => handleEdit(person)}>编辑</TextButton>
                <TextButton onClick={() => handleRemove(person)}>
                  删除
                </TextButton>
              </span>
            </li>
          ))}
        </ul>
      </div>
      {showAddDialog && (
        <Dialog title={editPerson ? '编辑' : '添加'}>
          <AddPerson />
        </Dialog>
      )}
    </AthletesContext.Provider>
  );
}
